package com.example.xianji.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.bean.YiJi_Class;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;

import android.os.Bundle;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Main_ChuangJain_FenLeiActivity extends Activity implements OnClickListener {
    /**
     * 创建分类
     */
    private Button button_chuangjian_fufenlei;
    private LinearLayout layout;
    private ListView show_listview;
    private PopupWindow show_popupWindow;
    private ArrayList<YiJi_Class> fenlei_list = new ArrayList<YiJi_Class>();
    private int pid = 0;
    private MyAdapter mMyAdapter;
    //    private SharedPreferences sp;
//    private Editor ed;
    private TextView submit_fenlei, chuangjian_fenlei_title;
    private EditText edittext_product_fenlei_name;
    private RelativeLayout relativelayout_chuangjian_fenlei_back;
    private ProgressDialog pd;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                show_listview.setAdapter(mMyAdapter);
                show_listview.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        pid = fenlei_list.get(position).getId();
                        button_chuangjian_fufenlei.setText(fenlei_list.get(position).getName());
                        if (show_popupWindow != null) {
                            show_popupWindow.dismiss();
                            show_popupWindow = null;
                        }
                    }
                });
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__chuang_jain__fen_lei);

        button_chuangjian_fufenlei = (Button) findViewById(R.id.button_chuangjian_fufenlei);
        chuangjian_fenlei_title = (TextView) findViewById(R.id.chuangjian_fenlei_title);
        submit_fenlei = (TextView) findViewById(R.id.submit_fenlei);
        edittext_product_fenlei_name = (EditText) findViewById(R.id.edittext_product_fenlei_name);
        relativelayout_chuangjian_fenlei_back = (RelativeLayout) findViewById(R.id.relativelayout_chuangjian_fenlei_back);
        pd = new ProgressDialog(this);

        button_chuangjian_fufenlei.setOnClickListener(this);
        submit_fenlei.setOnClickListener(this);
        relativelayout_chuangjian_fenlei_back.setOnClickListener(this);
        mMyAdapter = new MyAdapter();
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        if (getIntent().getIntExtra("fenlei_come_from", 0) == Contant.product_come_from_indefine_fenlei) {
            //来自于产品分类的编辑页面
            chuangjian_fenlei_title.setText("编辑分类");
            edittext_product_fenlei_name.setText(getIntent().getStringExtra("fenlei_title"));
            button_chuangjian_fufenlei.setText(getIntent().getStringExtra("fenlei_parent_name"));
            pid = getIntent().getIntExtra("parent_id", 0);
        } else {
            chuangjian_fenlei_title.setText("创建分类");
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button_chuangjian_fufenlei) {
            get_indefine_tag(1);
            Photo_show();
            show_popupWindow.showAtLocation(findViewById(R.id.chuangjian_fenlei_relative), Gravity.BOTTOM, 0, 0);
        } else if (v.getId() == R.id.submit_fenlei) {
            if (getIntent().getIntExtra("fenlei_come_from", 0) == Contant.product_come_from_indefine_fenlei) {
                //编辑产品分类
                pd.show();
                get_editor_fenlei_tag();
            } else {
                //创建产品分类
                pd.show();
                get_create_fenlei_tag();
            }

        } else if (v.getId() == R.id.relativelayout_chuangjian_fenlei_back) {
            Main_ChuangJain_FenLeiActivity.this.finish();
        }
    }

    public void get_indefine_tag(final int index) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("pid", 0);
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
//        map.put("token", sp.getString("xianji_token", ""));
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.indefine_felei,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        JSONArray array = response.getJSONArray("data");
                        fenlei_list.clear();
                        if (array.length() == 0) {
                            Toast.makeText(Main_ChuangJain_FenLeiActivity.this, "没有父分类, 请直接填写分类名称", Toast.LENGTH_SHORT).show();
                            if (show_popupWindow != null) {
                                show_popupWindow.dismiss();
                                show_popupWindow = null;
                            }
                        } else {
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject OBJECT = array.getJSONObject(i);
                                YiJi_Class mYiJi_Class = new YiJi_Class();
                                mYiJi_Class.setId(OBJECT.getInt("id"));
                                mYiJi_Class.setName(OBJECT.getString("name"));
                                fenlei_list.add(mYiJi_Class);
                            }
                            handler.sendEmptyMessage(index);

                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (show_popupWindow != null) {
                    show_popupWindow.dismiss();
                    show_popupWindow = null;
                }
                Toast.makeText(Main_ChuangJain_FenLeiActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    /**
     * 创建自定义分类
     */

    public void get_create_fenlei_tag() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("parent", pid);
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
//        map.put("token", sp.getString("xianji_token", ""));
        map.put("title", edittext_product_fenlei_name.getText().toString());
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.create_fenlei,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(Main_ChuangJain_FenLeiActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {
                        Main_ChuangJain_FenLeiActivity.this.finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    /**
     * 编辑自定义分类
     */
    public void get_editor_fenlei_tag() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("parent", pid);
        map.put("cat_id", getIntent().getIntExtra("cat_id", 0));
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
//        map.put("token", sp.getString("xianji_token", ""));
        map.put("title", edittext_product_fenlei_name.getText().toString());
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.editor_my_fenlei,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(Main_ChuangJain_FenLeiActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {
                        Contant.product_fenlei_editor_finish = 1;
                        Main_ChuangJain_FenLeiActivity.this.finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    private void Photo_show() {
        layout = (LinearLayout) LayoutInflater.from(
                Main_ChuangJain_FenLeiActivity.this).inflate(
                R.layout.information_shoow_photo, null);
        show_listview = (ListView) layout.findViewById(R.id.information_photo_listview);

        show_listview.setCacheColorHint(0);
        show_popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);

        show_popupWindow.setBackgroundDrawable(new BitmapDrawable());


        show_popupWindow.setHeight(400);
        show_popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        show_popupWindow.update();
        show_popupWindow.setOutsideTouchable(true);
        show_popupWindow.setFocusable(true);
        show_popupWindow.setContentView(layout);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        pd.cancel();
        pd = null;
        handler.removeCallbacksAndMessages(null);
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return fenlei_list.size();
        }

        @Override
        public Object getItem(int arg0) {
            return arg0;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder mHolder;
            if (convertView == null) {
                mHolder = new Holder();
                convertView = View.inflate(Main_ChuangJain_FenLeiActivity.this, R.layout.listview_item_layout, null);
                mHolder.place_text = (TextView) convertView.findViewById(R.id.place_text);
                convertView.setTag(mHolder);
            }
            mHolder = (Holder) convertView.getTag();
            mHolder.place_text.setText(fenlei_list.get(position).getName());
            return convertView;
        }
    }

    class Holder {
        TextView place_text;


    }
}
